//
//  WACustomImageCell.m
//  WeatherApp
//
//  Created by Yuliya Grasevych on 03.09.14.
//  Copyright (c) 2014 Yuliya Grasevych. All rights reserved.
//

#import "WACustomImageCell.h"

@implementation WACustomImageCell

-(void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
    if ([[self.image name] isEqualToString:@"no_image"]) {
        [super drawInteriorWithFrame:cellFrame inView:controlView];
        return;
    }
    NSSize imageSize = [self.image size];
    NSSize imageViewSize = controlView.bounds.size;
    
    NSSize scaledImageSize = imageSize;
    
    CGFloat imageAspectRatio = imageSize.height/imageSize.width;
    CGFloat imageViewAspectRatio = imageViewSize.height/imageViewSize.width;
    
    if (imageAspectRatio < imageViewAspectRatio) {
        // Image is more horizontal than the view. Image left and right borders need to be cropped.
        scaledImageSize.width = imageSize.height/imageViewAspectRatio;
    }
    else {
        // Image is more vertical than the view. Image top and bottom borders need to be cropped.
        scaledImageSize.height = imageSize.width*imageViewAspectRatio;
    }
    
    NSRect srcRect = NSMakeRect((imageSize.width-scaledImageSize.width) / 2.0,
                                (imageSize.height-scaledImageSize.height) / 2.0,
                                scaledImageSize.width,
                                scaledImageSize.height);
    
    [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
    
    [self.image drawInRect:controlView.bounds
                  fromRect:srcRect
                 operation:NSCompositeCopy
                  fraction:1.0
            respectFlipped:YES
                     hints:@{NSImageHintInterpolation: @(NSImageInterpolationHigh)}];
    
}
@end
